import { CACHE_USERINFO } from "@/global/constants"
import { localCache } from "@/utils/cacheData"
import { messageReminder } from "@/utils/notificationHint"
import { createRouter, createWebHashHistory } from "vue-router"

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: "/main/home"
    },
    {
      path: "/login-register",
      component: () => import("../views/login-register/login-register.vue")
    },
    {
      path: "/main",
      component: () => import("../views/main/main.vue"),
      children: [
        // 1 项目概览 project-overview
        {
          path: "home",
          name: "Home",
          component: () => import("../views/main/Home/Home.vue"),
          children: []
        },
        {
          path: "databases",
          name: "Databases",
          component: () => import("../views/main/Databases/Databases.vue"),
          children: []
        },
        {
          path: "audit",
          name: "Audit",
          component: () => import("../views/main/Audit/Audit.vue"),
          children: []
        },
        {
          path: "release",
          name: "Release",
          component: () => import("../views/main/Release/Release.vue"),
          children: []
        }
      ]
    },
    {
      path: "/roomParticulars",
      name: "RoomParticulars",
      component: () => import("../views/RoomInfo/roomParticulars.vue")
    },
    {
      path: "/articleInfoParticulars",
      name: "ArticleInfoParticulars",
      component: () => import("../views/ArticleInfo/articleInfoParticulars.vue")
    },
    {
      path: "/personalCenter",
      name: "personalCenter",
      component: () => import("../views/PersonalCenter/personalCenter.vue")
    },
    {
      path: "/:pathMatch(.*)",
      component: () => import("../views/404-NotFound/404-NotFound.vue")
    }
  ],
  // 每次切换路由页面滚回到顶部
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  const userInfo = localCache.getCache(CACHE_USERINFO)
  let isAdmin = false
  userInfo &&
    userInfo.authority.forEach((element) => {
      if (element.name == "Admin") {
        isAdmin = true
      }
    })
  if (to.name === "Audit" || to.name === "Release") {
    if (!userInfo) {
      messageReminder({
        message: "暂无用户信息，请先登录！",
        type: "error"
      })
    } else if (!isAdmin) {
      // 如果用户权限不是 Admin，则重定向到其他页面，比如首页
      messageReminder({
        message: "对不起，权限不足！",
        type: "error"
      })
    } else {
      // 用户权限为 Admin，允许进入 /audit 页面
      next()
    }
  } else {
    // 对于其他页面，直接放行
    next()
  }
})

export default router
